package com.teckteam.ptvsystem.view;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.teckteam.ptvsystem.controller.ScrapeFailedException;
import com.teckteam.ptvsystem.model.ResultNode;
import com.teckteam.ptvsystem.model.facade.PTVConstants;

/**
 * DIalog box for showing generated map of Journey
 * Reads from the Journey Plan Results object to generate map from Google using Static Maps API
 */
public class JourneyPlannerMapView extends JDialog
{
   public JourneyPlannerMapView(ArrayList<ResultNode> results) throws ScrapeFailedException
   {
      //TODO
      System.out.println("TBI: view map here");
      
      String drawLineArgs = "";
      ArrayList<String> nodeCoords = new ArrayList<String>();
      //separate nodes
      for(ResultNode r : results)
      {
         String details[] = r.getDestinationDetails(),
                coords[] = r.getCoordinates();
         
         drawLineArgs = drawLineArgs + String.format("|%s,%s", coords[0], coords[1]);
         nodeCoords.add(String.format("&markers=color:green|%s,%s", coords[0], coords[1]));
      }
      
      //TODO: collect coordinates paths between nodes
      
      //TODO: polyline encoding algorithm
      
      //pass to google maps static API
      String path = PTVConstants.MAP_URL + "&path=color:0x0000ff|weight:3";
      path = path + drawLineArgs;
      
      for(String s : nodeCoords)
         path = path + s;
      
      path = path.replaceAll("[|]", "%7C") + "&sensor=false";
      
      URL url;
      BufferedImage image = null;
      try
      {
         url = new URL(path);
         image = ImageIO.read(url);
         JPanel panel = new JPanel();
         panel.add(new JLabel(new ImageIcon(image)));
         add(panel);
         setSize(900,700);
         setVisible(true);
         setLocationRelativeTo(PTVUserInterface.getInstance());
      } catch (MalformedURLException e1)
      {
         e1.printStackTrace();
         throw new ScrapeFailedException();
      } catch(IOException e) 
      {
         System.out.println("Error occured : " + e.getMessage());       
      }
      
   }
}
